from rest_framework import serializers
from apps.users.models import User


class UserModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = "__all__"
        extra_kwargs = {
            'password': {'write_only': True},
            'id': {'read_only': True}
        }

    def create(self, validated_data):
        # 保存用户数据并对密码加密
        user = User.objects.create_user(**validated_data)
        return user

    def update(self, instance, validated_data):
        # 调用父类实现数据更新
        super().update(instance, validated_data)
        # 获取密码,并进行判断是否用户修改了密码
        password = validated_data.get('password')
        if password is not None:
            instance.set_password(password)
            instance.save()

        return instance


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ["id", "username", "password", "email", "maximum_borrowed", "borrowed"]
        extra_kwargs = {
            'password': {'write_only': True},
            'id': {'read_only': True},
            'borrowed': {'read_only': True},
            'maximum_borrowed': {'read_only': True}
        }

    def create(self, validated_data):
        # 保存用户数据并对密码加密
        user = User.objects.create_user(**validated_data)
        return user

    def update(self, instance, validated_data):
        # 调用父类实现数据更新
        super().update(instance, validated_data)
        # 获取密码,并进行判断是否用户修改了密码
        password = validated_data.get('password')
        if password is not None:
            instance.set_password(password)
            instance.save()

        return instance
